<template>
  <div class="login-page">
    <div class="left"></div>
    <div class="main">
      <h2 class="login_name">原生公司后台管理</h2>
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="demo-loginForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            type="text"
            class="captcha"
            v-model="loginForm.captcha"
            autocomplete="off"
          ></el-input>
          <span
            class="captcha-svg"
            v-html="captchasvg"
            @click="changesvg"
          ></span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="right">
      <video
        muted="muted"
        src="./../../assets/radio/vm5.mp4"
        autoplay="autoplay"
        loop="loop"
        preload="auto"
        class="bg_video"
      ></video>
    </div>
  </div>
</template>
<script>
//登录逻辑的实现

//1、收集用户的输入的信息  username &   password  传递给我们的后端
/**
 * 传递到后端
 */
//2、登录通过后呢，  将后端传过来的 token存储到本地中
//3、每次请求的时候，携带token
//4、展示token校验正确的数据，
//5、校验不通过 跳转到登录的页面

import { login, getCaptcha, refreshCaptcha, verifyCaptcha } from "@/api";
import { mapMutations } from "vuex";

export default {
  data() {
    //jsDoc的注释方式
    /**
     * @param {object} rule 就是一个表单验证的对象
     * @param {String} value 输入值
     * @param {function} callback  校验通过不传参,不通过
     */
    var validatausername = (rule, value, callback) => {
      console.log(rule);
      console.log(value);
      var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
      if (value === "") {
        callback("4到16位(字母,数字,下划线,减号)");
      } else {
        callback();
      }
      // if (value === '') {
      //   callback(new Error('请输入用户名'));
      // } else {
      //   if (this.loginForm.password !== '') {
      //     this.$refs.loginForm.validateField('password');
      //   }
      //   callback();
      // }
    };
    var validatePassword = (rule, value, callback) => {
      var uPattern = /^[a-zA-Z0-9_-]{6,8}$/;
      if (value === "") {
        callback("密码6-18组成(字母,数字)");
      } else {
        callback();
      }
    };
    //校验验证码
    var validateCaptcha = (rule, value, callback) => {
      if (value === "" || value.length !== 5) {
        callback("请输入正确的验证码");
      } else {
        callback();
      }
    };
    return {
      captchasvg: "", //从服务器 获取的验证码  svg

      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },

      rules: {
        username: [{ validator: validatausername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.set_captcha();
  },

  methods: {
    //映射vuex里面的内容
    ...mapMutations(["SET_USERINFO"]),

    //获取验证码
    set_captcha() {
      getCaptcha().then((res) => {
        console.log(res);
        this.captchasvg = res.data.img;
      });
    },
    //点击刷新验证码
    changesvg() {
      refreshCaptcha().then((res) => {
        this.captchasvg = res.data.img;
      });
    },

    submitForm(formName) {
      // console.log(this.$refs[formName]);
      //表单的登录逻辑
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开登录加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登录",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });

          console.log(this.loginForm.username);
          console.log(this.loginForm.password);
          login(this.loginForm.username, this.loginForm.password)
            .then((res) => {
              console.log(res);
              //服务器响应，关闭Lodding这个框框
              if (res.data.state) {
                verifyCaptcha(this.loginForm.captcha).then((req) => {
                  console.log(req);
                  if (req.data.state) {
                    this.$message({
                      showClose: true,
                      message: "登录成功",
                      type: "success",
                    });

                    loading.close();
                    localStorage.setItem("Lorenzo", res.data.token);
                    localStorage.setItem(
                      "Lorenzo-userInfo",
                      JSON.stringify(res.data.userInfo)
                    )
                      this.$store.commit('SET_PERMISSION_BUTTONS', res.data.permission.buttons)
                     localStorage.setItem('Lorenzo-permission-buttons', JSON.stringify(res.data.permission.buttons))
                      // 将用户信息储存到vuex中
                   
                    

                    //更改vues中 state ['userInfo']的值
                    this.SET_USERINFO(res.data.userInfo);
                    //跳转页面
                    this.$router.push("/welcome");
                  } else {
                    this.$message({
                      showClose: true,
                      message: "验证码密码错误",
                      type: "error",
                    });
                    this.changesvg()
                    loading.close();
                    localStorage.setItem("Lorenzo", "");
                  }
                });
              } else {
                //用户名密码错误
                this.$message({
                  showClose: true,
                  message: "用户名/密码错误",
                  type: "error",
                });
                loading.close();
                localStorage.setItem("Lorenzo", "");
              }
            })
            //统一的catch  我们会使用响应拦截器，我们在这里写  没事的
            .catch((err) => {
              setTimeout(() => {
                loading.close();
              }, 2000);
              this.$message({
                showClose: true,
                message: "错了哦，这是一条错误消息",
                type: "error",
              });
            });
          // alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
@import "../../assets/styles/login.css";
</style>
